package mqttx

import (
	"time"
	"github.com/eclipse/paho.mqtt.golang"

)

/*
 使用步骤
   1. NewMqtt
   2. Init
   3. 设置其他参数或者添加监听器
   4. Connect

  5. 做发布或者订阅
 */
type FinderMqtt struct {
	Clienter mqtt.Client
	Addr      string  // broke url
	Reconnect bool
	ClientId string
	UserName string
	Password string
	PublishHandler mqtt.MessageHandler
	ConnectHandler mqtt.OnConnectHandler
}

func NewFinderMqtt(addr string, reconnect bool,client_id string) *FinderMqtt {

	finderMq := &FinderMqtt{Addr: addr, Reconnect: reconnect,ClientId:client_id}
	return finderMq

}



func (this *FinderMqtt) Init()  {
	//"tcp://t.cnstartech.com:8883"
	/*clienter, err := client.CreateClient(client.MqttOption{
		Addr: this.Addr,
		//断开连接１秒后自动连接，０不自动重连
		ReconnTimeInterval: this.Reconnect,
		Clientid:           this.ClientId,
		UserName:this.UserName,
		CleanSession:false})*/

	opts :=mqtt.NewClientOptions().AddBroker(this.Addr).SetClientID(this.ClientId)
	opts.SetUsername(this.UserName)
	opts.SetKeepAlive(5*time.Second)
	opts.AutoReconnect=this.Reconnect
	opts.SetPingTimeout(2 * time.Second)
	opts.SetDefaultPublishHandler(this.PublishHandler)
	opts.SetOnConnectHandler(this.ConnectHandler)
	c := mqtt.NewClient(opts)
	this.Clienter=c


}

func (this *FinderMqtt) Connect() error {
	//建立连接
	/*err := this.Clienter.Connect()
	if err != nil {
		log.Fatal(err)
		//连接失败，不会进入自动重连状态
		panic(fmt.Errorf("连接失败:%v", err))
		return err
	}*/

	if token := this.Clienter.Connect(); token.Wait() && token.Error() != nil {
		return token.Error()
	}
	return nil
}





func (this *FinderMqtt) Subscribe(topic string, qos byte,callback mqtt.MessageHandler) error{
	// 10001是票代码
	//msgone/order/making/100001/+   接收 100001的挂单
	//msgone/order/making/+  接收挂单
	//mq, err := clienter.Subscribe("msgone/order/making/+", client.QoS1)

	token := this.Clienter.Subscribe(topic, qos,callback)

	if token.Wait() && token.Error() != nil {
		return token.Error()
	}
	return nil
}

func (this *FinderMqtt) Publish(topic string,qos byte,retained bool,payload interface{}) error{
	token := this.Clienter.Publish(topic, qos, retained, payload)
	token.Wait()
	return token.Error()
}

func (this *FinderMqtt) Close() {

	//移除事件
	this.Clienter.Disconnect(1)


}
